<template>
  <el-form :model="form" label-width="0" :rules="rules" ref="registerForm">
    <el-form-item prop="username">
      <el-input v-model="form.username" :maxlength="32" placeholder="手机号码/邮箱"/>
    </el-form-item>
    <el-form-item prop="password1">
      <el-input type="password" :maxlength="32" v-model="form.password1" placeholder="设置密码，3-32位"/>
    </el-form-item>
    <el-form-item prop="password2">
      <el-input type="password" :maxlength="32" v-model="form.password2" placeholder="确认密码，3-32位"/>
    </el-form-item>
    <el-form-item prop="imageCode">
      <el-input type="imageCode" :maxlength="6" v-model="form.imageCode" placeholder="请输入图片验证码">
        <!--suppress HtmlUnknownTarget -->
        <img class="imageCode" alt="imageCode" slot="append" :src="imageCodeUrl" @click="freshImageCode"/>
      </el-input>
    </el-form-item>
    <el-form-item prop="code">
      <el-input type="text" :maxlength="6" :minlength="6" v-model="form.code" placeholder="请输入短信验证码">
        <template slot="append">
          <el-button class='btnGetCode' @click="getRegisterCode('registerForm')" :loading="codeLoading"
                     :disabled="codeButtonDisabled">
            {{codeButtonMessage}}
          </el-button>
        </template>
      </el-input>
    </el-form-item>
    <el-button type="primary" @click="register('registerForm')" :loading="loading"
               :disabled="loading" class="btn" style="width: 100%">
      Register
    </el-button>
    <p v-if="showToLogin" class="login-link">
      Have an account, <span @click="toLogin" class="link">Log In now!</span>
    </p>
  </el-form>
</template>

<script>
import regexp from '@/utils/RegexpUtils'
import { registerCode, requestRegister } from '@/api/ApiUser'
import sysConfig from '@/config/sysConfig'

export default {
  name: 'FormLogin',
  props: ['showToLogin'],
  data () {
    const validUsername = (rule, value, callback) => {
      if (value.indexOf('@') !== -1) {
        if (!regexp.validEmail(value)) {
          callback(new Error('不是合法的邮箱地址'))
        }
      } else {
        if (!regexp.validPhone(value)) {
          callback(new Error('不是合法的手机号码'))
        }
      }
      return callback()
    }
    const validPassword1 = (rule, value, callback) => {
      this.$refs.registerForm.validateField('password2')
      callback()
    }
    const validPassword2 = (rule, value, callback) => {
      if (!value) {
        callback()
      }
      if (this.form.password1 !== value) {
        callback(new Error('密码不一致'))
      }
      return callback()
    }
    return {
      loading: false,
      codeLoading: false,
      codeTime: 0,
      imageCodeFresh: new Date().getTime(),
      form: {
        username: '',
        password1: '',
        password2: '',
        code: '',
        imageCode: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入手机号码或者可用的邮箱', trigger: 'blur' },
          { min: 3, max: 32, message: '长度在 3 到 32 个字符', trigger: 'blur' },
          { validator: validUsername, trigger: 'blur' }
        ],
        password1: [
          { required: true, message: '请设置密码', trigger: 'blur' },
          { min: 3, max: 32, message: '密码长度在 3 到 32 个字符', trigger: 'blur' },
          { validator: validPassword1, trigger: 'blur' }
        ],
        password2: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { min: 3, max: 32, message: '密码长度在 3 到 32 个字符', trigger: 'blur' },
          { validator: validPassword2, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '验证码不能为空', trigger: 'blur' },
          { min: 6, max: 6, message: '验证码为六位数字', trigger: 'blur' },
          { pattern: /^[0-9]{6}$/, message: '验证码为六位数字', trigger: 'blur' }
        ],
        imageCode: [
          { required: true, message: '验证码不能为空', trigger: 'blur' },
          { pattern: '^[0-9a-zA-Z]{4,6}$', message: '验证码是4-6个数字或字母组成的字符串', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    toLogin () {
      this.$emit('toLogin')
    },
    getRegisterCode (formName) {
      const vm = this
      let fieldsToValidate = ['username', 'imageCode']
      Promise.all(fieldsToValidate.map(item => {
        return new Promise(resolve => {
          this.$refs[formName].validateField(item, (error) => {
            resolve(error)
          })
        })
      })).then(data => {
        let m = data.join('').length === 0
        if (m) {
          vm.codeLoading = true
          // 注册验证码
          registerCode(vm.form.username, vm.form.imageCode, () => {
            vm.codeLoading = false
            vm.$message({
              message: '获取验证码成功',
              type: 'success'
            })
            vm.codeTime = 10
            const internalId = setInterval(() => {
              vm.codeTime--
              if (vm.codeTime === 0) {
                clearInterval(internalId)
              }
            }, 1000)
          }, () => {
            vm.codeLoading = false
          })
        }
      })
    },
    register (formName) {
      const vm = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          vm.loading = true
          requestRegister(vm.form.username, vm.form.password1, vm.form.code, () => {
            this.$emit('success')
            vm.$confirm('注册成功,是否前往登陆？', '成功', {
              type: 'success',
              confirmButtonText: '前往登陆',
              callback: action => {
                if (action === 'confirm') {
                  vm.$emit('toLogin')
                }
              }
            })
          }, () => {
            vm.loading = false
          })
        }
      })
    },
    freshImageCode () {
      this.imageCodeFresh = new Date().getTime()
    }
  },
  computed: {
    codeButtonDisabled () {
      return this.codeTime > 0 || this.codeLoading
    },
    codeButtonMessage () {
      if (this.codeLoading) {
        return '正在获取'
      } else if (this.codeTime > 0) {
        return '剩余 ' + this.codeTime + ' s'
      } else {
        return '获取验证码'
      }
    },
    imageCodeUrl () {
      return sysConfig.baseUrl + '/middle-user/user/imageCode?key=register&temp=' + this.imageCodeFresh + ')'
    }
  },
  mounted () {
    this.freshImageCode()
  }
}
</script>

<style lang="scss" scoped>
  .login-link {
    margin-top: 20px;
    color: #777777;
    user-select: none;

    .link {
      color: #444444;
      cursor: pointer;
      margin-left: 4px;
    }

    .link:hover {
      color: darksalmon
    }

  }

  .btnGetCode {
    width: 120px;
    text-align: center;
  }

  .imageCode {
    cursor: pointer;
    width: 80px;
    height: 32px;
    display: inline-block;
    background-size: 100% 100%;
  }
</style>
